import { Button, Form, Input, Modal } from "antd";
import { useForm } from "antd/lib/form/Form";
import { useEffect, useState } from "react";
import { useDeleteTask, useUpdateTask } from "../../../api/task";
import { TaskTypeSelect } from "../../../components/task-type-select";
import { UserSelect } from "../../../components/user-select";
import { useTaskModal, useTaskQueryKey } from "./utils";

export const TaskModal = () => {
  const { visible, close, taskDetailData } = useTaskModal();
  const [form] = useForm();
  const { isLoading: updateLoading, mutateAsync: updateMutateAsync } =
    useUpdateTask(useTaskQueryKey());
  const { isLoading: deleteLoding, mutateAsync: deleteMutateAsync } =
    useDeleteTask(useTaskQueryKey());
  const isLoading = updateLoading || deleteLoding;

  const onClose = () => {
    form.resetFields();
    close();
  };

  const onSubmit = (formValue: any) => {
    updateMutateAsync({
      ...taskDetailData,
      ...formValue,
    }).then(onClose);
  };

  const handleDelete = () => {
    Modal.confirm({
      title: "确定删除？",
      cancelText: "取消",
      okText: "确定",
      onOk: () => deleteMutateAsync(taskDetailData).then(onClose),
    });
  };

  useEffect(() => {
    form.setFieldsValue(taskDetailData);
  }, [taskDetailData, form]);

  return (
    <Modal
      title="编辑任务"
      cancelText="取消"
      okText="确定"
      confirmLoading={isLoading}
      forceRender
      open={visible}
      onCancel={onClose}
      onOk={() => form.submit()}
    >
      <Form
        form={form}
        labelAlign="right"
        labelCol={{ span: 4 }}
        onFinish={onSubmit}
      >
        <Form.Item
          label="任务名"
          name="name"
          rules={[{ required: true, message: "请输入任务名" }]}
        >
          <Input placeholder="请输入任务名" />
        </Form.Item>
        <Form.Item label="经办人" name="processorId">
          <UserSelect defaultName="经办人" />
        </Form.Item>
        <Form.Item label="类型" name="typeId">
          <TaskTypeSelect defaultName="类型" />
        </Form.Item>
      </Form>
      <div style={{ textAlign: "right" }}>
        <Button
          style={{ fontSize: "14px", marginLeft: "auto" }}
          size="small"
          danger
          onClick={handleDelete}
        >
          删除
        </Button>
      </div>
    </Modal>
  );
};
